import React, { useEffect, useRef } from "react";
import pointIcon from '@/assets/point.png';


interface ChildProps {
    data: { type: string; value: [] };
}
const BMapComponent: React.FC<ChildProps> = ({ data }) => {
    const mapRef = useRef<HTMLDivElement>(null);
    const map = useRef<any>(null); // 地图实例
    const polylines = useRef<any>(null); // 当前绘制路线
    const allpoints = useRef<any>([]); // 所有点位
    // const drivingService = useRef<any>(null)
    useEffect(() => {
        // 确保地图加载完成后再初始化oint
        const initMap = () => {
            if (!mapRef.current) return;
            map.current = new window.BMapGL.Map(mapRef.current);
            // 设置中心点
            const point = new window.BMapGL.Point(116.405, 39.920);
            map.current.centerAndZoom(point, 11);
            // 启用滚轮缩放
            map.current.enableScrollWheelZoom(true);
            // 添加控件
            map.current.addControl(new window.BMapGL.ZoomControl());
            map.current.addControl(new window.BMapGL.ScaleControl())
        };
        // 判断是否已经加载了 BMapGL
        if (window.BMapGL && window.BMapGL.Map) {
            initMap();
        } else {
            // 如果未加载，定义全局回调
            window.BMapGL.onBMapLoad = () => {
                initMap();
            };
        }
    }, []);
    useEffect(() => {
        if (data.type == 'polyline') {
            createPolyline(data.value)
        }
        if (data.type == 'point') {
            createPoints(data.value)
        }
    }, [data]);


    //绘制地图中心点
    const setCenter = (obj: any) => {
        const point = new window.BMapGL.Point(obj.lng, obj.lat);
        map.current.centerAndZoom(point, 11);
    }

    //绘制点位
    const createPoints = (arr: any) => {
        setCenter(arr[0])
        arr.forEach((i: any) => {
            const myIcon = new window.BMapGL.Icon(
                pointIcon,
                new window.BMapGL.Size(20, 30),
                {
                    anchor: new window.BMapGL.Size(10, 20)
                }
            );
            let point = new window.BMapGL.Point(i.lng, i.lat)
            let marker = new window.BMapGL.Marker(point, { icon: myIcon });
            const content = `
                   <div style="padding: 10px; margin-top: -16px">
                   <h4 style="margin: 0 0 5px 0;">${i.place}</h4>
                   <p style="margin: 0; font-size: 12px;">经纬度：${i.lng}, ${i.lat}</p>
                  </div>
                  `
            // 创建信息窗口
            const infoWindow = new window.BMapGL.InfoWindow(content, {
                width: 50,
                height: 70,
                title: "",
                offset: new window.BMapGL.Size(0, -10), // 向上偏移 10 像素
            });
            marker.addEventListener("click", () => {
                map.current.openInfoWindow(infoWindow, point);
            });
            map.current?.addOverlay(marker);
            allpoints.current.push(marker)
        })
    }
    //绘制当前线路
    // const createPolyline = (arr: any) => {
    //     // 1. 清理之前的路线和标记
    //     if (drivingService.current) {
    //         drivingService.current.clearResults(); //清除所有自动绘制的 Overlay
    //         drivingService.current = null
    //     }
    //     clearAllMarkers(); // 清除所有标记点
    //     // createPoints(arr)
    //     if (arr.length < 2) {
    //         console.warn("至少需要两个点才能规划路线");
    //         return;
    //     }

    //     // 3. 创建驾车路线服务实例
    //     drivingService.current = new window.BMapGL.DrivingRouteLine(map.current, {
    //         renderOptions: {
    //             map: map.current,
    //             autoViewport: true,// 是否自动调整地图视野
    //             // enableDragging: true,
    //         },
    //         policy: 0,
    //         onSearchComplete: function (results: any) {
    //             // 路线规划完成后的回调函数
    //             if (drivingService.current.getStatus() === window.BMAP_STATUS_SUCCESS) {
    //                 // 获取第一条路线（通常是最优路线）
    //                 console.log(results, '结果')
    //                 console.log("路线总数：" + results.getNumPlans());
    //                 console.log(results.getPlan(0).getDuration(true), '驾驶时间')
    //                 console.log(results.getPlan(0).getDistance(true), '驾驶距离')

    //                 // 创建 Polyline，DrivingRouteLine会自动添加线路，也可手动添加
    //                 //const firstRoute = results.getPlan(0).getRoute(0);
    //                 // const pathPoints = firstRoute.getPath();
    //                 // const realPolyline = new window.BMapGL.Polyline(pathPoints, {
    //                 //     strokeStyle: 'solid',
    //                 //     strokeColor: '#758DD1', // 初始颜色
    //                 //     strokeWeight: 8,
    //                 //     strokeOpacity: 0.8,
    //                 // });
    //                 // 5. 将路线添加到地图
    //                 // map.current.addOverlay(realPolyline);
    //                 // polylines.current = realPolyline;

    //                 // 6. 设置地图中心到第一个点 (可选，也可以让路线服务自动调整视野)
    //                 // setCenter(arr[0]);

    //                 // let currentColor = '#758DD1';
    //                 // const intervalId = setInterval(() => {
    //                 //     currentColor = currentColor === '#758DD1' ? '#7BAD8D' : '#758DD1';
    //                 //     if (polylines.current) {
    //                 //         polylines.current.setStrokeColor(currentColor);
    //                 //     } else {
    //                 //         clearInterval(intervalId); // 如果 polyline 被清除，停止定时器
    //                 //     }
    //                 // }, 400);
    //             } else {
    //                 console.error("路线规划失败:", drivingService.current.getStatus());
    //             }
    //         }
    //     });
    //     const start = new window.BMapGL.Point(arr[0].lng, arr[0].lat);
    //     const end = new window.BMapGL.Point(arr[arr.length - 1].lng, arr[arr.length - 1].lat);
    //     const waypoints = arr.slice(1, arr.length - 1).map((point: any) =>
    //         new window.BMapGL.Point(point.lng, point.lat)
    //     );
    //     // 发起路线规划请求

    //     drivingService.current.search(start, end, { waypoints: waypoints, tactics: 2 });
    // };
    const createPolyline = (arr: any) => {
        if (polylines.current) {
            map.current.removeOverlay(polylines.current);
            polylines.current = null
        }
        clearAllMarkers()
        createPoints(arr)
        setCenter(arr[0])
        let currentColor = '#758DD1';
        let data = arr.map((i: any) => {
            return new window.BMapGL.Point(i.lng, i.lat)
        })
        let polyline = new window.BMapGL.Polyline(data, {
            strokeStyle: 'solid',
            strokeColor: currentColor,
            strokeWeight: 8,
            strokeOpacity: 0.8,
        });
        map.current.addOverlay(polyline);
        polylines.current = polyline
        setInterval(() => {
            currentColor = currentColor === '#758DD1' ? '#7BAD8D' : '#758DD1';
            polyline.setStrokeColor(currentColor);
        }, 400);
    }




    //清除所有点位
    const clearAllMarkers = () => {
        const overlays = map.current.getOverlays();
        overlays.forEach((i: any) => {
            if (i instanceof window.BMapGL.Marker) {
                map.current.removeOverlay(i);
            }
        });
        allpoints.current = []
    };

    return <div ref={mapRef}
        style={{ width: '100%', height: '100%', border: '1px solid #ccc' }}></div>


}

export default BMapComponent






